package com.google.code.UtopiaXml;

/**
 * Class representing xs:element with maxOccurs>1.
 *
 * @author Michael Simacek
 */
public class MultiElement extends Element {

    /**
     * Creates element with given name and type
     *
     * @param type type of element
     * @param name original (unconverted) name of the element
     */
    public MultiElement(Type type, String name) {
        super(name, new ListProperty(type, name));
    }

    @Override
    public void generateParserBlock(CodeBuilder cb, String parentObject, String nodeName) {
        cb.appendLine("//begin MultiElement");
        String resName = getName() + "Object";
        String listName = getName() + "List";
        cb.appendLine("List<" + getType().getTypeName() + "> " + listName + " = new ArrayList<>();");
        cb.addImport("java.util.List");
        cb.addImport("java.util.ArrayList");

        cb.appendLine("do {");
        getType().appendLoaderFromElement(cb, nodeName, resName);
        cb.appendLine(listName + ".add(" + resName + ");");
        cb.appendLine(nodeName + " = getNextElement(" + nodeName + ");");
        cb.appendLine("} while (" + nodeName + " != null && \"" + getElementName()
                      + "\".equals(" + nodeName + ".getNodeName()));");

        cb.appendLine(parentObject + ".set" + CodeBuilder.toUpperCamelCase(getName()) + "(" + listName + ");");
        cb.appendLine("//end MultiElement");
    }
}
